package com.hmall.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.config.AuthProperties;
import com.hmall.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;


@RequiredArgsConstructor
@Component
@EnableConfigurationProperties(AuthProperties.class)
public class MyglobFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher =  new AntPathMatcher();
    private final JwtTool jwtTool;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if(isexclude(request.getPath().toString())){
            return chain.filter(exchange);

        }

        String token = request.getHeaders().getFirst("Authorization");

        try {
            Long userid = jwtTool.parseToken(token);
            // 将用户信息写入到请求头
            String string = userid.toString();
            exchange.mutate().request(new Consumer<ServerHttpRequest.Builder>() {
                @Override
                public void accept(ServerHttpRequest.Builder builder) {
                    builder.header("userinfo",string);
                }
            });

        }catch (Exception e){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }

        return chain.filter(exchange);


    }

    private boolean isexclude(String string) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath,string)){

                return true;
            }
        }

        return false;

//            for (String excludePath : authProperties.getExcludePaths()) {
//                if(antPathMatcher.match(excludePath,string)){
//                    return true;
//                }
//
//            }
//            return false;

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
